package com.tq.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

public class IpUtils {
	// 判断ip是否正确
	public boolean validIP(String ip) {
		boolean isIP = true;

		String[] itemIp = ip.split("\\.");
		if (itemIp.length != 4) {
			isIP = false;
		} else {
			String temp = itemIp[0] + itemIp[1] + itemIp[2] + itemIp[3];
			for (int j = 0; j < temp.length(); j++) {
				if (!(temp.charAt(j) >= 48 && temp.charAt(j) <= 57)) {
					return false;
				}
			}
			int itemIpOne = Integer.valueOf(itemIp[0]);
			int itemIpTwo = Integer.valueOf(itemIp[1]);
			int itemIpThree = Integer.valueOf(itemIp[2]);
			int itemIpFour = Integer.valueOf(itemIp[3]);

			if (itemIpOne <= 255 && itemIpTwo <= 255 && itemIpThree <= 255
					&& itemIpFour <= 255 && itemIpOne >= 1 && itemIpTwo >= 0
					&& itemIpThree >= 0 && itemIpFour >= 0) {
				isIP = true;
			} else {
				isIP = false;
			}
		}
		return isIP;
	}
	
	//获取本机无线ip
//	WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
//	//获取本机ip
//	mWifitIpTextView.setText("本机IP:" + new WifiLocalIp().getWifiLocalIp(wifiManager);
	public String getWifiLocalIp(WifiManager wifiManager) {

		if (!wifiManager.isWifiEnabled()) {

			wifiManager.setWifiEnabled(true);

		}

		WifiInfo wifiInfo = wifiManager.getConnectionInfo();

		int ipAddress = wifiInfo.getIpAddress();

		String ipAddressCom = (ipAddress & 0xFF) + "." +

		((ipAddress >> 8) & 0xFF) + "." +

		((ipAddress >> 16) & 0xFF) + "." +

		(ipAddress >> 24 & 0xFF);

		return ipAddressCom;
	}
	//获取到本地的ip
	public String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
			Log.e("WifiPreference IpAddress", ex.toString());
		}
		return null;
	}
	
}
